#include "timer.h"

#define LSB(i) ((i) & 0xFF)    ///< The Least Significative Byte of a Word
#define MSB(i) ((i) >> 8)      ///< The Most Significative Byte of a Word


void timer_init(int timer, int mode)
{
	outportb(TIMER_CTRL, mode | (timer << 6));
	if(timer==2)
		outportb(SPEAKER_CTRL, inportb(SPEAKER_CTRL)|TIMER2_ENABLE);
}

/** Load timer (0,1,2) with value
 */
void timer_load(int timer, int value)
{
	if(timer==0)
	{
		outportb(TIMER_0,LSB(value));
		outportb(TIMER_0,MSB(value));
	}
	if(timer==2)
	{
		outportb(TIMER_2,LSB(value));
		outportb(TIMER_2,MSB(value));
	
	}
}

/** Wait mili miliseconds, indirectly counting T0 interrupts
*/
void mili_sleep(int mili)
{
	int final=msec+mili;
	while(msec<final);
}

/** wait secs seconds, indirectly counting T0 interrupts
 */
void sec_sleep(int secs)
{
	mili_sleep(secs*1000);
}

int get_divider(double freq)
{
	if ( freq <= 0)
		return -1;
	return (int) TIMER_CLK / freq + 0.5;
}

